package com.pks.datacenter.config;

import java.util.StringJoiner;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.pks.resultful.common.SRemoteResult;
import com.pks.resultful.common.SResultCode;
import com.pks.web.context.BasicWebContext;
import com.pks.web.dto.ServiceResult;

@RestController
@ControllerAdvice
public class WebExceptionHandler {

	private static final Logger logger = LoggerFactory
			.getLogger(WebExceptionHandler.class);

	@ResponseBody
	@ExceptionHandler(value = UnPermException.class)
	public SRemoteResult<String> unPerm(UnPermException e) {
		return SRemoteResult.initErrorNoPerm();
	}

	@ExceptionHandler
	public String error(HttpServletRequest request, Exception ex,
			HttpServletResponse response, Model model) {
		logger.error(ex.getMessage(), ex);
		boolean ajax = BasicWebContext.isWebAjaxRequest(request);
		boolean noHandlerFound = (ex instanceof org.springframework.web.servlet.NoHandlerFoundException);
		String errorString = noHandlerFound ? "请求地址错误" : "服务器内部错误："
				+ ex.getMessage();
		if (ajax) {
			try {
				response.getWriter().write(
						ServiceResult.initErrorJson(errorString));
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
			return null;
		}
		model.addAttribute("error", errorString);
		return noHandlerFound ? "error/404" : "error/500";
	}

	@ExceptionHandler(MethodArgumentNotValidException.class)
	public SRemoteResult<String> handleMethodArgumentNotValidException(
			MethodArgumentNotValidException e) {
		// 获取所有的错误
		// List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
		// 获取错误提示
		// System.out.println(fieldErrors.get(0).getDefaultMessage());
		// 获取错误字段
		// System.out.println(fieldErrors.get(0).getField());

		// 将所有的错误提示使用";"拼接起来并返回
		StringJoiner sj = new StringJoiner(";");
		e.getBindingResult().getFieldErrors().forEach(x -> sj.add(x.getDefaultMessage()));
		return SRemoteResult.initCustom(SResultCode.PARAM_IS_INVALID.getCode(), sj.toString());
	}

//	@ExceptionHandler(ConstraintViolationException.class)
//	public SRemoteResult<String> handleConstraintViolationException(
//			ConstraintViolationException e) {
//		StringJoiner sj = new StringJoiner(";");
//		e.getConstraintViolations().forEach(x -> sj.add(x.getMessage()));
//
//		return SRemoteResult.initCustom(SResultCode.PARAM_IS_INVALID.getCode(), sj.toString());
//	}
	

}
